package com.cmc.cloud.cmclink.doc.service.impl.si;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoVslvoyErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.convert.BlnoVslvoyConvert;
import com.cmc.cloud.cmclink.doc.entity.BlnoVslvoyDO;
import com.cmc.cloud.cmclink.doc.mapper.BlnoVslvoyMapper;
import com.cmc.cloud.cmclink.doc.service.si.BlnoVslvoyService;
import com.cmc.cloud.cmclink.doc.vo.blnovo.BlnoTransferVO;
import com.cmc.cloud.cmclink.doc.vo.blnovslvoyvo.BlnoVslvoyCreateReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnovslvoyvo.BlnoVslvoyPageReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnovslvoyvo.BlnoVslvoyUpdateReqVO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 提单航线船期信息 Service 实现类
 *
 * @author 集运管理员
 */
@Service
@Validated
public class BlnoVslvoyServiceImpl implements BlnoVslvoyService {

    @Resource
    private BlnoVslvoyMapper blnoVslvoyMapper;

    private static final String CONNECTOR = "-";

    @Override
    public void createBlnoVslvoy(BlnoVslvoyCreateReqVO createReqVO) {
        // 插入
        BlnoVslvoyDO blnoVslvoy = BlnoVslvoyConvert.INSTANCE.convert(createReqVO);
        blnoVslvoyMapper.insert(blnoVslvoy);
    }

    @Override
    public void updateBlnoVslvoy(BlnoVslvoyUpdateReqVO updateReqVO) {
        // 校验存在
        validateBlnoVslvoyExists(updateReqVO.getId());
        // 更新
        BlnoVslvoyDO updateObj = BlnoVslvoyConvert.INSTANCE.convert(updateReqVO);
        blnoVslvoyMapper.updateById(updateObj);
    }

    @Override
    public void deleteBlnoVslvoy(Long id) {
        // 校验存在
        validateBlnoVslvoyExists(id);
        // 删除
        blnoVslvoyMapper.deleteById(id);
    }
    @Override
    public void deleteBlnoVslvoyByblnoId(Long blnoId) {
        LambdaQueryWrapper<BlnoVslvoyDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoVslvoyDO::getBlnoId, blnoId);
        blnoVslvoyMapper.delete(queryWrapper);
    }

    private void validateBlnoVslvoyExists(Long id) {
        if (blnoVslvoyMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(BlnoVslvoyErrorCodeConstants.BLNO_VSLVOY_NOT_EXISTS);
        }
    }

    @Override
    public BlnoVslvoyDO getBlnoVslvoy(Long id) {
        return blnoVslvoyMapper.selectById(id);
    }

    @Override
    public List<BlnoVslvoyDO> getBlnoVslvoyBySiId(Long id) {
        LambdaQueryWrapper<BlnoVslvoyDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoVslvoyDO::getBlnoId, id);
        queryWrapper.orderByAsc(BlnoVslvoyDO::getId);
        return blnoVslvoyMapper.selectList(queryWrapper);
    }

    @Override
    public List<BlnoVslvoyDO> getBlnoVslvoyBySiIdList(Collection<Long> ids) {
        LambdaQueryWrapperX<BlnoVslvoyDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.in(BlnoVslvoyDO::getBlnoId, ids);
        return blnoVslvoyMapper.selectList(queryWrapperX);
    }

    @Override
    public List<BlnoVslvoyDO> getBlnoVslvoyList(Collection<Long> ids) {
        return blnoVslvoyMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BlnoVslvoyDO> getBlnoVslvoyPage(BlnoVslvoyPageReqVO reqVO) {
        IPage<BlnoVslvoyDO> page = Page.of(reqVO.getPageNo(), reqVO.getPageSize());

        IPage<BlnoVslvoyDO> result = blnoVslvoyMapper.selectPageList(page, reqVO);
        return new PageResult<BlnoVslvoyDO>(result.getRecords(), result.getTotal());
    }

    @Override
    public void createOrUpdateAndDeleteBatch(Long blnoId, List<BlnoVslvoyUpdateReqVO> newList, List<BlnoVslvoyUpdateReqVO> oldList) {
        // 无效数据直接返回
        if (CollectionUtil.isEmpty(newList) && CollectionUtil.isEmpty(oldList)) {
            return;
        }
        // 默认值
        if (CollectionUtil.isEmpty(newList)) {
            newList = new ArrayList<>();
        }
        if (CollectionUtil.isEmpty(oldList)) {
            oldList = new ArrayList<>();
        }
        List<BlnoVslvoyUpdateReqVO> createList = new ArrayList<>();
        List<BlnoVslvoyUpdateReqVO> updateList = new ArrayList<>();
        Set<String> createSet = new HashSet<>();
        // 历史数据
        Set<Long> oldIds = oldList.stream().map(e -> e.getId()).collect(Collectors.toSet());
        newList.forEach(e -> {
            if (e.getId() != null) {
                if (oldIds.contains(e.getId())) {
                    // 正常更新
                    updateList.add(e);
                    oldIds.remove(e.getId()); // 剩下的数据需要删除
                } else {
                    // 数据更新非法
                    throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.SI_NI_UPDATE);
                }
            } else {
                if (blnoVslvoyMapper.selectCount(new LambdaQueryWrapper<BlnoVslvoyDO>()
                        .eq(BlnoVslvoyDO::getBlnoId, blnoId)
                        .eq(BlnoVslvoyDO::getPolCode, e.getPolCode())
                        .eq(BlnoVslvoyDO::getPodCode, e.getPodCode())
                ) <= 0) {
                    e.setBlnoId(blnoId);
                    if (createSet.contains(e.getBlnoId() + CONNECTOR + e.getPolCode() + CONNECTOR + e.getPodCode())) {
                        throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.SI_NI_CREATE_REPEAT);
                    }
                    createSet.add(e.getBlnoId() + CONNECTOR + e.getPolCode() + CONNECTOR + e.getPodCode());
                    createList.add(e);
                }
            }
        });
        if (CollectionUtil.isNotEmpty(oldIds)) {
            // 没有匹配上的就是前端删除的
            blnoVslvoyMapper.deleteBatchIds(oldIds);
        }
        if (CollectionUtil.isNotEmpty(createList)) {
            List<BlnoVslvoyDO> siVslvoyCreateList = BeanUtil.copyToList(createList, BlnoVslvoyDO.class);
            blnoVslvoyMapper.insertBatch(siVslvoyCreateList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            List<BlnoVslvoyDO> siVslvoyUpdateList = BeanUtil.copyToList(updateList, BlnoVslvoyDO.class);
            blnoVslvoyMapper.updateBatch(siVslvoyUpdateList);
        }
    }

    @Override
    public List<BlnoVslvoyDO> getBlnoVslvoyInfo(Long id) {
        LambdaQueryWrapper<BlnoVslvoyDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoVslvoyDO::getBlnoId, id);
        queryWrapper.orderByAsc(BlnoVslvoyDO::getRouteNo);
        return blnoVslvoyMapper.selectList(queryWrapper);
    }

    @Override
    public void updateBlnoVslvoyTrans(BlnoTransferVO reqVO) {
        LambdaQueryWrapperX<BlnoVslvoyDO> queryWrapper = new LambdaQueryWrapperX<>();
        queryWrapper.in(BlnoVslvoyDO::getBlnoId, reqVO.getBlIds());
        queryWrapper.eq(BlnoVslvoyDO::getPolCode, reqVO.getTransPort());
        List<BlnoVslvoyDO> blnoVslvoyDOList = blnoVslvoyMapper.selectList(queryWrapper);
        blnoVslvoyDOList.forEach(vslvoy -> {
            vslvoy.setVesselCode(reqVO.getBkgVesselCode());
            vslvoy.setVoyageEx(reqVO.getVoyageEx());
            vslvoy.setVoyageIm(reqVO.getVoyageIm());
        });
        blnoVslvoyMapper.updateBatch(blnoVslvoyDOList);
    }

    @Override
    public BlnoVslvoyDO showBlnoVslvoy(BlnoTransferVO reqVO) {
        LambdaQueryWrapperX<BlnoVslvoyDO> queryWrapper = new LambdaQueryWrapperX<>();
        queryWrapper.eqIfPresent(BlnoVslvoyDO::getBlnoId, reqVO.getBlId());
        queryWrapper.eq(BlnoVslvoyDO::getPolCode, reqVO.getTransPort());
        queryWrapper.orderByDesc(BlnoVslvoyDO::getCreateTime).last("LIMIT 1");
        return blnoVslvoyMapper.selectOne(queryWrapper);
    }

}
